package cn.fl.finance.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.finance.api.IFinPayApplyInfoApiService;
import cn.fl.finance.api.IFinPayDtlRApiService;
import cn.fl.finance.condition.*;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.finance.constant.FinPayApplyInfoConstant;
import cn.fl.finance.dto.FinPayApplyInfoDTO;
import cn.fl.finance.dto.FinPayDtlRDTO;
import cn.fl.finance.service.*;
import cn.fl.finance.vo.*;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.system.service.ISysEmpBankAccService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysEmpBankAccVO;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import cn.fl.upload.constant.UploadConstant;
import fl.ass.facade.constant.AssFileConstant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 借款申请服务
 * 作者:hongyanbo
 * 时间:2018/9/28
 */
@Service
public class FinLoanApplyServiceImpl implements IFinLoanApplyService {
    public static final Logger LOGGER = LoggerFactory.getLogger(FinLoanApplyServiceImpl.class);
    @Autowired
    private IFinPayApplyInfoApiService finPayApplyInfoApiService;
    @Autowired
    private IFinLoanInfoService finLoanInfoService;
    @Autowired
    private IFinLoanDtlService finLoanDtlService;
    @Autowired
    private IFinPayDtlService finPayDtlService;
    @Autowired
    private IFinPayApplyInfoService finPayApplyInfoService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysEmpBankAccService bankAccService;
    @Autowired
    private IFinPayDtlRService payDtlRService;
    @Autowired
    private IFinPayDtlRApiService payDtlRApiService;
    @Autowired
    private ISysUsrService usrService;
	@Autowired
	private IUploadApiService uploadApiService;
    @Override
    public Map<String,Long> saveOrUpdateLoanDtl(String loanDtlJsonList, Long loanInfoId,Long applyInfoId,String newFlag,String fileParams) {
        Map<String,Long> result = new HashMap<>();
        List<FinLoanDtlVO> finLoanDtlVOS ;
        if(newFlag.equals("1")){
            finLoanDtlVOS = parseJson2List(loanDtlJsonList);
        }else{
            FinLoanDtlQC qc = new FinLoanDtlQC();
            qc.setLoanId(loanInfoId);
            finLoanDtlVOS = this.finLoanDtlService.selectList(qc);
        }
        if(loanInfoId == null){
            // add loan info
            loanInfoId = addFinLoanInfo(finLoanDtlVOS);
        }else{
            // update
            updateFinLoanInfo(finLoanDtlVOS,loanInfoId);
        }
        if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
            for (FinLoanDtlVO finLoanDtlVO : finLoanDtlVOS) {
                finLoanDtlVO.setLoanId(loanInfoId);
            }
        }
        result.put("loanInfoId",loanInfoId);
        // 全删全插的修改方式
        // 删除fin-loan-dtl
        if(StringUtils.isNotBlank(newFlag) && newFlag.equals("1")){ //只有第一次新建申请的时候允许修改loanDtl
            this.finLoanDtlService.deleteByLoanInfoId(loanInfoId);
            if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
                // add loan dtl
                for (FinLoanDtlVO finLoanDtlVO : finLoanDtlVOS) {
                    Long id = finLoanDtlService.add(finLoanDtlVO);
                    finLoanDtlVO.setId(id);
                }
            }
        }
        // add pay apply
        if(applyInfoId == null){
            applyInfoId = addPayApply(loanInfoId);
        }
        result.put("payApplyId",applyInfoId);
        //deleteByLoanInfoId pay dtl
        if(applyInfoId!=null){
            this.finPayDtlService.deleteByApplyId(applyInfoId);
        }
        // add pay dtl is_del=2
        genPayDtl(finLoanDtlVOS,applyInfoId,newFlag);
        saveFile(fileParams,applyInfoId);
        return result;
    }

    private void saveFile(String fileParams, Long applyInfoId) {
    	String property = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
    	List<SysUlFilesRecVO> fileList = null;
    	if(StringUtils.isNotEmpty(fileParams)){
            fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
    	}
		// 上传附件
    	SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
    	qc.setPkId(applyInfoId.toString());
    	boolean b = uploadApiService.removeSysUlFilesRecByCondition(qc);
		if(CollectionUtils.isNotEmpty(fileList)){
			for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
				if(sysUlFilesRecVO.getFilePath().contains(property)){
					sysUlFilesRecVO.setFilePath(sysUlFilesRecVO.getFilePath().replace(property, ""));
				}
				sysUlFilesRecVO.setTabNm(FinPayApplyInfoConstant.TAB_NM);
				sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
				sysUlFilesRecVO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
				sysUlFilesRecVO.setCfgCd(FinPayApplyInfoConstant.FIN_PAY_APPLY_INFO_CFGCD);
				sysUlFilesRecVO.setCfgDtlCd(FinPayApplyInfoConstant.FIN_PAY_APPLY_INFO_CFGDTLCD_1);
				sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
				sysUlFilesRecVO.setPkId(applyInfoId.toString());
				sysUlFilesRecVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				sysUlFilesRecVO.setCrtTm(new Date());
				sysUlFilesRecVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				sysUlFilesRecVO.setMdfTm(new Date());
				uploadApiService.addSysUlFilesRec(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
			}
		}
	}

	private void updateFinLoanInfo(List<FinLoanDtlVO> finLoanDtlVOS, Long loanInfoId) {
        FinLoanInfoVO finLoanInfoVO = assembleFinLoanInfo(finLoanDtlVOS);
        finLoanInfoVO.setId(loanInfoId);
        this.finLoanInfoService.modify(finLoanInfoVO);
    }


    @Override
    public List<FinPayDtlGridVO> selectPayDtlGridList(Long payApplyId, String newFlag) {
        if(payApplyId==null){
            throw new BaseException("参数不完整");
        }
        List<FinPayDtlVO> payDtlVOList = getFinPayDtlVOS(payApplyId);
        Map<Long, FinPayDtlVO> finPayDtlVOMap = toMap(payDtlVOList);
        List<FinLoanDtlVO> finLoanDtlVOS = getFinLoanDtlVOS(payDtlVOList);
        List<FinPayDtlGridVO> resultList = new ArrayList<>();
        // 查字典
        // 借款类型
        Map<String, String> loanTypMap = this.sysDictionaryApiService.searchGroupToMap(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.FIN_LOAN_TYP_DIDC);
        //付款方式
        Map<String, String> payWayCd = this.sysDictionaryApiService.searchGroupToMap(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.FIN_PAY_TYP_DIDC);
        // 拼装
        if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
            for (FinLoanDtlVO dtlVO : finLoanDtlVOS) {
                FinPayDtlGridVO vo = new FinPayDtlGridVO();

                vo.setLoanAmt(dtlVO.getLoanAmt());
                vo.setLoanTypCd(loanTypMap.get(dtlVO.getLoanTypCd()));
                vo.setPayTypCd(payWayCd.get(dtlVO.getPayTypCd()));
                FinPayDtlVO payDtlVO = finPayDtlVOMap.get(dtlVO.getId());
                if(payDtlVO!=null){
                    Long amtLeft = getAmtLeft(dtlVO,payDtlVO.getId());
                    vo.setAmtLeft(DecimalUtils.convertFenToYuan(amtLeft));
                    vo.setId(payDtlVO.getId());
                    vo.setPayAmt(DecimalUtils.convertFenToYuan(payDtlVO.getPayAmt()));
                    vo.setAccNo(payDtlVO.getAccNo());
                    vo.setBkId(payDtlVO.getBkId());
                    vo.setPayeeBkNo(payDtlVO.getPayeeBkNo());
                    vo.setPayeeBkNm(payDtlVO.getPayeeBkNm());
                    vo.setRcptUnt(payDtlVO.getRcptUnt());

                    // 查询绑定资产数量
                    FinPayDtlRQC qc = new FinPayDtlRQC();
                    qc.setPayDtlId(payDtlVO.getId());
                    List<FinPayDtlRVO> finPayDtlRVOS = payDtlRService.selectList(qc);
                    if(CollectionUtils.isNotEmpty(finPayDtlRVOS)){
                        vo.setAssetCount(finPayDtlRVOS.size());
                    }else{
                        vo.setAssetCount(0);
                    }
                }

                resultList.add(vo);
            }
        }
        return resultList;
    }

    @Override
    public DataResultVO bindBankAcc(Long payDtlId, Long bankAccId) {
        DataResultVO resultVO = new DataResultVO();
        // 1.查询账户信息
        SysEmpBankAccVO bankAccVO = this.bankAccService.selectById(bankAccId);
        // 2.更新付款明细
        if(bankAccVO!=null){
            FinPayDtlVO payDtl = new FinPayDtlVO();
            payDtl.setId(payDtlId);
            payDtl.setBkId(bankAccVO.getId());
            payDtl.setRcptUnt(bankAccVO.getRcptUnt());
            payDtl.setAccNo(bankAccVO.getAccNo());
            payDtl.setPayeeBkNo(bankAccVO.getBkNo());
            payDtl.setPayeeBkNm(bankAccVO.getBkNm());
            String accTypCd = bankAccVO.getAccTypCd();
            if(StringUtils.isBlank(accTypCd)){
                resultVO.setSuccess(0);
                resultVO.setInfo("绑定失败，请维护账户类型。");
                return resultVO;
            }
            payDtl.setBkAccTypCd(accTypCd);
            payDtl.setMdfTm(new Date());
            payDtl.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            this.finPayDtlService.modify(payDtl);
            resultVO.setSuccess(1);
            resultVO.setInfo("绑定成功");
            resultVO.setData(null);
        }else{
            resultVO.setSuccess(0);
            resultVO.setInfo("绑定失败，查询银行账户信息失败。");
            resultVO.setData(null);
            BaseLogUtils.info(LOGGER,"bindBankAcc","绑定失败，查询银行账户信息失败。");
        }
        return resultVO;
    }

    @Override
    public void updatePayDtlList(String json) {
        List<FinPayDtlVO> payDtlVOList = JSON.parseArray(json, FinPayDtlVO.class);
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                finPayDtlService.modify(payDtlVO);
            }
        }
    }

    @Override
    public DataResultDTO save(String action, Long payApplyId, int confirm) {
        DataResultDTO res = new DataResultDTO("200","暂存成功");
        // 更新 fin_pay_apply_info
        FinPayApplyInfoVO applyInfoVO = this.finPayApplyInfoService.selectById(payApplyId);
        applyInfoVO.setIsDel(0);
        if(action.equals("2")){ //保存但是不发起流程
            applyInfoVO.setPayStsCd("1");
        }else{
            applyInfoVO.setPayStsCd(action);
        }
        // 查询 fin_pay_dtl
        FinPayDtlQC qc = new FinPayDtlQC();
        qc.setPayApplyId(payApplyId);
        List<FinPayDtlVO> payDtlVOList = this.finPayDtlService.selectList(qc);
        if(CollectionUtils.isEmpty(payDtlVOList)){
            return new DataResultDTO("204","数据不完整");
        }
        applyInfoVO.setPayAmt(DecimalUtils.convertFenToYuan(getSummary(payDtlVOList)));
        // 校验 总借款金额不能大于借款申请金额
        boolean valid = validate(applyInfoVO,payDtlVOList);
        if(!valid){
            return new DataResultDTO("201","保存失败，付款总额不能大于借款总额。");
        }
        // 校验 是否绑定银行卡
        boolean valid2 = validateBankAcc(payDtlVOList);
        if(!valid2){
            return new DataResultDTO("201","保存失败，请先绑定银行卡信息。");
        }



        // 校验 借款明细本次申请金额 大于小于或等于 资产绑定使用金额
        int i = validAsset(payDtlVOList);
        if(i ==1){ // 平均分配
            if(confirm ==1){ //user点击确认平均分配
                saveAssetBind(payDtlVOList);
            }else{
                return new DataResultDTO("202","本次付款金额超出已绑定资产使用金额合计，请调整已绑定资产；如不更改，本次付款金额将平均分配至已绑定资产！");
            }
        }
        if(i ==-1){ // 提示重新维护资产绑定信息
            return new DataResultDTO("203","已绑定资产使用金额超出本次付款金额，请调整！");
        }
        if(!valid){
            return new DataResultDTO("201","保存失败，付款总额不能大于借款总额，且金额必须大于0。");
        }
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                payDtlVO.setIsDel(0);
            }
        }
        this.finPayApplyInfoService.modify(applyInfoVO);
        this.finPayDtlService.batchModify(payDtlVOList);

        if(action.equals("1")){ //提交付款审批
            // 调用流程startflow
            res = startFlow(payApplyId);
        }
        return res;
    }

    /**
     * 验证是否全部绑定了银行卡
     *
     * @param payDtlVOList
     * @return
     */
    private boolean validateBankAcc(List<FinPayDtlVO> payDtlVOList) {
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                Long bkId = payDtlVO.getBkId();
                if(bkId == null){
                    return false;
                }
            }
            return true;
        }
        return false;
    }


    /**
     * 均分资产绑定金额
     * @param payDtlVOList
     */
    private void saveAssetBind(List<FinPayDtlVO> payDtlVOList) {
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                FinPayDtlRQC qc = new FinPayDtlRQC();
                qc.setPayDtlId(payDtlVO.getId());
                List<FinPayDtlRDTO> finPayDtlRDTOS = this.payDtlRApiService.selectList(qc);
                this.payDtlRService.saveAssetBind(payDtlVO.getId(),payDtlVO,finPayDtlRDTOS);
            }
        }

    }

    /**
     * 1：存在  申请金额 大于 资产绑定使用金额
     * -1 ：存在 申请金额 小于 资产绑定使用金额
     * 0：一切正常
     * @param payDtlVOList
     * @return
     */
    private int validAsset(List<FinPayDtlVO> payDtlVOList) {
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                FinPayDtlRQC qc = new FinPayDtlRQC();
                qc.setPayDtlId(payDtlVO.getId());
                List<FinPayDtlRVO> list = this.payDtlRService.selectList(qc);
                Long sum =0l;
                if(CollectionUtils.isNotEmpty(list)){
                    for (FinPayDtlRVO finPayDtlRVO : list) {
                        sum+=finPayDtlRVO.getPayAmt();
                    }
                }else{
                    throw new BaseException("请先绑定资产");
                }
                if(payDtlVO.getPayAmt() > sum){
                    return 1;// 有剩余金额未分配
                }
                if(payDtlVO.getPayAmt() < sum){
                    return -1; //资产使用金额过大
                }
            }

        }
        return 0;
    }

    private Long getSummary(List<FinPayDtlVO> payDtlVOList) {
        Long sum =0l;
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                sum += payDtlVO.getPayAmt();
            }
        }
        return sum;
    }

    private boolean validate(FinPayApplyInfoVO applyInfoVO, List<FinPayDtlVO> payDtlVOList) {
        FinLoanInfoVO finLoanInfoVO = this.finLoanInfoService.selectById(applyInfoVO.getLoanId());
        // 可申请总金额
        Long total = finLoanInfoVO.getLoanAmt();
        if(total == null || total==0l){
            return false; //校验申请金额必须大于0
        }
        // 已经申请的金额
        Long applyedAmtSumarry = getApplyedAmtSumarry(applyInfoVO.getLoanId(),applyInfoVO.getId());
        total = total-applyedAmtSumarry;
        // 本次申请金额
        Long sum = 0l;
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                sum += payDtlVO.getPayAmt();
            }
            if(sum<=total){
                return true;
            }
        }
        return false;
    }

    /**
     *  发起借款流程
     * @param payApplyId
     */
    @Override
    public DataResultDTO startFlow(Long payApplyId) {
        FinFlowUserInfoQC param = new FinFlowUserInfoQC();
        param.setId(payApplyId);
        param.setCurrentBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
        param.setCurrentOrgCd(CurrentThreadContext.getCurrentOrgCd());
        param.setCurrentOrgDispNm(CurrentThreadContext.getCurrentOrgDispNm());
        param.setCurrentSysCd(CurrentThreadContext.getCurrentSysCd());
        param.setCurrentUserId(CurrentThreadContext.getCurrentUserId());
        param.setCurrentUserName(CurrentThreadContext.getCurrentUserName());
        return finPayApplyInfoApiService.addFlowStart(param);
    }

    @Override
    public Long selectTempApplyIdByLoanInfoId(String loanInfoId) {
        FinPayApplyInfoQC qc = new FinPayApplyInfoQC();
        qc.setLoanId(Long.valueOf(loanInfoId));
        qc.setIsDel("2");
        List<FinPayApplyInfoDTO> list = this.finPayApplyInfoService.selectList(qc);
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0).getId();
        }
        return null;
    }

    /**
     * 获取已经申请过的金额
     *
     * @param loanId
     * @param payApplyId
     * @return
     */
    private Long getApplyedAmtSumarry(Long loanId, Long payApplyId){
        Long res = 0l;
        FinPayApplyInfoQC qc = new FinPayApplyInfoQC();
        qc.setLoanId(loanId);
        qc.setIsDel("0");
        List<String> payStsCd = new ArrayList<>();
        payStsCd.add("1");// 申请中
        payStsCd.add("2");// 放款中
        payStsCd.add("3");// 已经放款
        qc.setPayStsCdList(payStsCd);
        qc.setNotId(payApplyId);
            List<FinPayApplyInfoDTO> list = this.finPayApplyInfoService.selectList(qc);
        if(CollectionUtils.isNotEmpty(list)){
            for (FinPayApplyInfoDTO applyInfoDTO : list) {
                res += applyInfoDTO.getPayAmt();
            }
        }
        return res;
    }
    private Map<Long, FinPayDtlVO> toMap(List<FinPayDtlVO> payDtlVOList) {
        Map<Long,FinPayDtlVO> finPayDtlVOMap = new HashMap<>();
        for (FinPayDtlVO payDtlVO : payDtlVOList) {
            finPayDtlVOMap.put(payDtlVO.getLoanDtlId(),payDtlVO);
        }
        return finPayDtlVOMap;
    }

    private List<FinLoanDtlVO> getFinLoanDtlVOS(List<FinPayDtlVO> payDtlVOList) {
        List<FinLoanDtlVO> finLoanDtlVOS = null;
        if(CollectionUtils.isNotEmpty(payDtlVOList)){
            // 查 finLoanDtl
            List<Long> loanDtlIds = new ArrayList<>();
            for (FinPayDtlVO payDtlVO : payDtlVOList) {
                loanDtlIds.add(payDtlVO.getLoanDtlId());
            }
            if(CollectionUtils.isNotEmpty(loanDtlIds)){
                FinLoanDtlQC dtlQC = new FinLoanDtlQC();
                dtlQC.setIds(loanDtlIds);
                finLoanDtlVOS = this.finLoanDtlService.selectList(dtlQC);
            }
        }
        return finLoanDtlVOS;
    }

    private List<FinPayDtlVO> getFinPayDtlVOS(Long payApplyId) {
        FinPayDtlQC qc = new FinPayDtlQC();
        qc.setPayApplyId(payApplyId);
        return this.finPayDtlService.selectList(qc);
    }

    /**
     * 添加付款申请
     */
    private Long addPayApply(Long infoId) {
        FinPayApplyInfoVO applyInfoVO = new FinPayApplyInfoVO();
        applyInfoVO.setIsDel(2);
        applyInfoVO.setLoanId(infoId);
//            applyInfoVO.setLoanNo();
        applyInfoVO.setPayAmt(0d);
        applyInfoVO.setPayStsCd(FinLoanConstant.FIN_PAY_STS_CD_0);
        applyInfoVO.setCrtTm(new Date());
        applyInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        return finPayApplyInfoService.add(applyInfoVO);
    }

    /**
     * 生成付款明细
     * @param finLoanDtlVOS
     * @param newFlag
     */
    private  List<FinPayDtlVO> genPayDtl(List<FinLoanDtlVO> finLoanDtlVOS, Long payApplyId, String newFlag) {
        List<FinPayDtlVO> payDtlVOList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
            for (FinLoanDtlVO finLoanDtlVO : finLoanDtlVOS) {
                FinPayDtlVO dtlVO = new FinPayDtlVO();
                dtlVO.setIsDel(2);
                if(newFlag.equals("1")){//首次申请
                    dtlVO.setPayAmt(DecimalUtils.convertYuanToFen(finLoanDtlVO.getLoanAmt()));
                }else{// 多次申请，需要扣除以往申请金额作为本次申请的默认金额
                    Long amtLeft = getAmtLeft(finLoanDtlVO,null);
                    dtlVO.setPayAmt(amtLeft);
                }
                dtlVO.setLoanDtlId(finLoanDtlVO.getId());
                dtlVO.setPayApplyId(payApplyId);
                payDtlVOList.add(dtlVO);
                Long id = finPayDtlService.add(dtlVO);
                dtlVO.setId(id);
            }
        }
        return payDtlVOList;
    }

    /**
     * 获取剩余可申请金额
     * @param finLoanDtlVO
     * @param exceptId 不等于这个ID
     */
    private Long getAmtLeft(FinLoanDtlVO finLoanDtlVO,Long exceptId) {
        FinPayDtlQC qc = new FinPayDtlQC();
        qc.setLoanDtlId(finLoanDtlVO.getId());
        qc.setIsDel(0l);
        qc.setExceptId(exceptId);
        List<FinPayDtlVO> list = this.finPayDtlService.selectList(qc);
        Long sum = getSummary(list);
        return DecimalUtils.convertYuanToFen(finLoanDtlVO.getLoanAmt()-(sum/100));
    }

    private Long addFinLoanInfo(List<FinLoanDtlVO> finLoanDtlVOS) {
        FinLoanInfoVO finLoanInfoVO = assembleFinLoanInfo(finLoanDtlVOS);
        return finLoanInfoService.add(finLoanInfoVO);
    }

    private FinLoanInfoVO assembleFinLoanInfo(List<FinLoanDtlVO> finLoanDtlVOS) {
        FinLoanInfoVO finLoanInfoVO = new FinLoanInfoVO();
        finLoanInfoVO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
        finLoanInfoVO.setCstMgrOrgCd(CurrentThreadContext.getCurrentOrgCd());
        finLoanInfoVO.setCstMgrNm(CurrentThreadContext.getCurrentUserName());
        finLoanInfoVO.setCstMgrId(CurrentThreadContext.getCurrentUserId());
        Long usrId = CurrentThreadContext.getCurrentUserId();
        SysUsrVO sysUsrVO = usrService.selectById(usrId,"11000");
        finLoanInfoVO.setCstMgrCd(sysUsrVO.getUsrNm());
        finLoanInfoVO.setLoanStsCd(FinLoanConstant.FIN_LOAN_STS_CD_0);

        Double amtSummary = getAmtSummary(finLoanDtlVOS);
        finLoanInfoVO.setLoanAmt(DecimalUtils.convertYuanToFen(amtSummary));
        finLoanInfoVO.setLoanTm(new Date());
        finLoanInfoVO.setCstMgrRgnCd(CurrentThreadContext.getCurrentRgnDivCd());
        return finLoanInfoVO;
    }

    /**
     * 计算总金额
     * @param finLoanDtlVOS
     */
    private Double getAmtSummary(List<FinLoanDtlVO> finLoanDtlVOS) {
        Double res = 0d;
        if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
            for (FinLoanDtlVO finLoanDtlVO : finLoanDtlVOS) {
                Double loanAmt = finLoanDtlVO.getLoanAmt();
                if(loanAmt!=null){
                    res += loanAmt;
                }
            }
        }
        return res;
    }

    private List<FinLoanDtlVO> parseJson2List(String json){
        if(StringUtils.isNotBlank(json)){
            List<FinLoanDtlVO> finLoanDtlVOS = JSONArray.parseArray(json, FinLoanDtlVO.class);
            if(CollectionUtils.isNotEmpty(finLoanDtlVOS)){
                return finLoanDtlVOS;
            }
        }
        return null;
    }

    @Override
    public DataResultDTO saveConfirm(Long payApplyId) {
        FinPayApplyInfoVO applyInfoVO = this.finPayApplyInfoService.selectById(payApplyId);
        FinPayDtlQC qc = new FinPayDtlQC();
        qc.setPayApplyId(applyInfoVO.getId());
        List<FinPayDtlVO> payDtlVOList = this.finPayDtlService.selectList(qc);


        return null;
    }
}
